package com.ailianlian.ablecisi.activity;

import android.content.Intent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.ailianlian.ablecisi.R;
import com.ailianlian.ablecisi.adapter.CommentAdapter;
import com.ailianlian.ablecisi.adapter.RelatedArticleAdapter;
import com.ailianlian.ablecisi.baseclass.BaseActivity;
import com.ailianlian.ablecisi.constant.ExtrasConstant;
import com.ailianlian.ablecisi.databinding.ActivityArticleDetailBinding;
import com.ailianlian.ablecisi.pojo.entity.Article;
import com.ailianlian.ablecisi.pojo.entity.Comment;
import com.ailianlian.ablecisi.utils.ImageLoader;
import com.ailianlian.ablecisi.utils.LoginInfoUtil;
import com.ailianlian.ablecisi.utils.MarkDownUtil;
import com.ailianlian.ablecisi.utils.TimeAgoUtil;
import com.ailianlian.ablecisi.viewmodel.ArticleViewModel;
import com.google.android.material.chip.Chip;

/**
 * 文章详情页面
 */
public class ArticleDetailActivity extends BaseActivity<ActivityArticleDetailBinding> {

    private ArticleViewModel viewModel;
    private CommentAdapter commentAdapter;
    private RelatedArticleAdapter relatedArticleAdapter;
    private String currentReplyToCommentId;
    private String articleId;
    private boolean isFollowing;

    @Override
    protected ActivityArticleDetailBinding getViewBinding() {
        return ActivityArticleDetailBinding.inflate(getLayoutInflater());
    }

    private void getViewModel() {
        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ArticleViewModel.class);
    }

    @Override
    protected void initView() {
        getViewModel(); // 获取ViewModel实例

        articleId = getIntent().getStringExtra(ExtrasConstant.EXTRA_ARTICLE_ID);

        // 设置工具栏
        setSupportActionBar(binding.toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }

        setupCommentAdapter();// 初始化评论适配器
        setupRelatedArticleAdapter(); // 初始化相关文章适配器
        observeViewModel();// 观察数据变化

    }

    @Override
    protected void initData() {
        // 获取文章ID并加载文章
        if (articleId == null) {
            showToast("文章ID不能为空");
            finish();
        }
        viewModel.loadArticle(articleId); // 加载文章数据
    }

    @Override
    protected void setListeners() {
        setupClickListeners();
    }

    private void setupClickListeners() {
        setupCommentListener(); // 设置评论监听器
        setupRelatedArticleListener(); // 设置相关文章监听器
        // 关注按钮
        binding.btnFollow.setOnClickListener(v -> {
            isFollowing = !isFollowing;
            System.out.println("当前关注状态: " + isFollowing);
            updateFollowButton(isFollowing);
            viewModel.followAuthor(isFollowing); // 调用ViewModel方法处理关注逻辑
        });

        // 点赞按钮
        binding.btnLike.setOnClickListener(v -> {
            viewModel.likeArticle();
        });

        // 评论按钮
        binding.btnComment.setOnClickListener(v -> {
            binding.editComment.requestFocus();
        });

        // 分享按钮
        binding.btnShare.setOnClickListener(v -> {
            shareArticle();
        });

        // 收藏按钮
        binding.btnBookmark.setOnClickListener(v -> {
            viewModel.bookmarkArticle();
        });

        // 发送评论按钮
        binding.btnSendComment.setOnClickListener(v -> {
            String commentContent = binding.editComment.getText().toString().trim();
            if (commentContent.isEmpty()) {
                Toast.makeText(this, R.string.article_comment_empty, Toast.LENGTH_SHORT).show();
                return;
            }
            viewModel.addComment(commentContent, currentReplyToCommentId);// 发送评论
            binding.editComment.setText("");// 清空输入框
            currentReplyToCommentId = null;
            binding.layoutComment.setHint(R.string.article_comment_hint);// 重置回复状态
        });
    }

    private void setupCommentAdapter() {
        commentAdapter = new CommentAdapter(this);
        binding.rvComments.setAdapter(commentAdapter);
    }

    private void setupCommentListener() {
        commentAdapter.setOnCommentActionListener(new CommentAdapter.OnCommentActionListener() {
            @Override
            public void onReplyClicked(Comment comment) {
                currentReplyToCommentId = comment.getId();// 设置当前回复的评论ID
                binding.layoutComment.setHint(getString(R.string.article_reply) + " " + comment.getUserName()); // 更新评论输入框提示
                binding.editComment.requestFocus();// 聚焦到评论输入框
            }

            @Override
            public void onLikeClicked(Comment comment) {
                viewModel.likeComment(comment.getId()); // 点赞评论
            }
        });
    }

    private void setupRelatedArticleAdapter() {
        relatedArticleAdapter = new RelatedArticleAdapter();
        binding.rvRelatedArticles.setAdapter(relatedArticleAdapter);
    }

    private void setupRelatedArticleListener() {
        relatedArticleAdapter.setOnArticleClickListener(article -> {
            // 跳转到相关文章详情页
            Intent intent = new Intent(ArticleDetailActivity.this, ArticleDetailActivity.class);
            intent.putExtra(ExtrasConstant.EXTRA_ARTICLE_ID, article.getId());
            startActivity(intent);
        });
    }

    private void updateFollowButton(boolean isFollowing) {
        if (isFollowing) {
            binding.btnFollow.setText(R.string.following);
            binding.btnFollow.setBackgroundColor(getResources().getColor(R.color.white, null));
            binding.btnFollow.setTextColor(getResources().getColor(R.color.primary, null));
        } else {
            binding.btnFollow.setText(R.string.follow);
            binding.btnFollow.setBackgroundColor(getResources().getColor(R.color.primary, null));
            binding.btnFollow.setTextColor(getResources().getColor(R.color.white, null));
        }
    }

    // 观察文章数据
    private void observeViewModel() {

        // 更新UI
        viewModel.getArticle().observe(this, this::updateArticleUI);

        // 观察相关文章数据
        viewModel.getRelatedArticles().observe(this, articles -> {
            relatedArticleAdapter.submitList(articles);
        });

        // 观察加载状态
        viewModel.getIsLoading().observe(this, isLoading -> {
            binding.loadingOverlay.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        });

        // 观察评论加载状态
        viewModel.getIsCommentLoading().observe(this, isLoading -> {
            binding.btnSendComment.setEnabled(!isLoading);
        });

        // 观察错误消息
        viewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });

        // 观察评论成功状态
        viewModel.getCommentSuccess().observe(this, success -> {
            if (success) {
                Toast.makeText(this, R.string.article_comment_success, Toast.LENGTH_SHORT).show();
            }
        });

        // 观察关注状态
        viewModel.getIsFollowing().observe(this, isFollowing -> {
            this.isFollowing = isFollowing; // 更新当前关注状态
            updateFollowButton(isFollowing);
        });

        // 观察评论
        viewModel.getCommentsGlobal().observe(this, comments -> {
            commentAdapter.submitList(comments); // 更新评论列表
            binding.tvNoComments.setVisibility(comments.isEmpty() ? View.VISIBLE : View.GONE); // 显示无评论提示
        });
    }

    private void updateArticleUI(Article article) {
        if (article == null) return;

        viewModel.loadFollowStatus(article.getId());
        viewModel.loadRelatedArticles(article.getId());

        // 设置文章标题
        binding.tvTitle.setText(article.getTitle());

        // 设置作者信息
        binding.tvAuthorName.setText(article.getAuthorName());
        binding.tvPublishTime.setText(TimeAgoUtil.toTimeAgo(article.getPublishTime()));
        ImageLoader.load(this, article.getAuthorAvatarUrl(), binding.ivAuthorAvatar, R.drawable.ic_profile, R.drawable.ic_profile);

         // 设置作者头像
        String avatarUrl = LoginInfoUtil.getAvatarUrl(this);
        ImageLoader.load(this, avatarUrl, binding.ivUserAvatar, R.drawable.ic_profile, R.drawable.ic_profile);

        // 设置文章标签
        binding.chipGroupTags.removeAllViews();
        for (String tag : article.getTags()) {
            Chip chip = new Chip(this);
            chip.setText(tag);
            chip.setClickable(false);
            chip.setChipBackgroundColorResource(R.color.primary_light);
            chip.setTextColor(getResources().getColor(R.color.text_primary, null));
            binding.chipGroupTags.addView(chip);
        }

        // 设置文章内容
        MarkDownUtil.setMarkdown(this, binding.tvContent, article.getContent()); // 使用Markwon渲染Markdown内容

        // 设置文章统计信息
        binding.tvViewCount.setText(article.getViewCount() + " 阅读");
        binding.tvCommentCount.setText(article.getCommentCount() + " 评论");
        binding.tvLikeCount.setText(article.getLikeCount() + " 点赞");
        updateLikeButton(article.getLiked());// 设置点赞状态
        updateBookmarkButton(article.getBookmarked());// 设置收藏状态
        commentAdapter.submitList(article.getComments());// 设置评论列表

        binding.tvNoComments.setVisibility(article.getComments().isEmpty() ? View.VISIBLE : View.GONE);// 显示无评论提示
    }

    private void updateLikeButton(boolean isLiked) {
        if (isLiked) {
            binding.btnLike.setText(R.string.article_liked);
            binding.btnLike.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_heart_filled, 0, 0, 0);
            binding.btnLike.setTextColor(getResources().getColor(R.color.primary, null));
        } else {
            binding.btnLike.setText(R.string.article_like);
            binding.btnLike.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_heart, 0, 0, 0);
            binding.btnLike.setTextColor(getResources().getColor(R.color.text_primary, null));
        }
    }

    private void updateBookmarkButton(boolean isBookmarked) {
        if (isBookmarked) {
            binding.btnBookmark.setText(R.string.article_bookmarked);
            binding.btnBookmark.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_bookmark_filled, 0, 0, 0);
            binding.btnBookmark.setTextColor(getResources().getColor(R.color.primary, null));
        } else {
            binding.btnBookmark.setText(R.string.article_bookmark);
            binding.btnBookmark.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_bookmark_border, 0, 0, 0);
            binding.btnBookmark.setTextColor(getResources().getColor(R.color.text_primary, null));
        }
    }

    private void shareArticle() {
        Article article = viewModel.getArticle().getValue();
        if (article == null) return;

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, article.getTitle());
        shareIntent.putExtra(Intent.EXTRA_TEXT, article.getTitle() + "\n\n" + article.getContent().substring(0, Math.min(100, article.getContent().length())) + "...");
        startActivity(Intent.createChooser(shareIntent, getString(R.string.article_share)));
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            getOnBackPressedDispatcher().onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 